package com.cloudlinkscm.base.filecenter.domain;

import com.cloudlinkscm.base.filecenter.dao.FileStreamDao;
import com.cloudlinkscm.base.filecenter.model.FileRecord;
import com.cloudlinkscm.base.filecenter.model.FileStream;
import com.cloudlinkscm.base.filecenter.model.SysAuthCode;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 文件流manager
 *
 * @author : tac
 * @date : 2017/7/24
 */
@Component
public class FileStreamManager {
    public FileStreamDao dao;
    private SysAuthCodeManager sysAuthCodeManager;
    private static final int TIMEOUT_SECOND = 30;

    @Autowired
    public FileStreamManager(FileStreamDao dao, SysAuthCodeManager sysAuthCodeManager) {
        this.dao = dao;
        this.sysAuthCodeManager = sysAuthCodeManager;
    }

    public FileStream createStream(FileRecord record, StoredLocationBuilder storedLocationBuilder){
        FileStream stream = new FileStream();
        stream.setFileId(record.getId());
        stream.setStorageType(record.getStorageType());
        stream.setExpiredTime(getExpiredTime());
        stream.setFileLocation(storedLocationBuilder.build(record.getLocation(), sysAuthCodeManager.getOrThrow(record.getSysCode())));
        stream.setFileName(record.getName() + "." + record.getExt());
        dao.insert(stream);
        return stream;
    }

    private Date getExpiredTime() {
        DateTime dateTime = new DateTime();
        dateTime = dateTime.plusSeconds(TIMEOUT_SECOND);
        return dateTime.toDate();
    }

    public boolean isExpired(FileStream stream) {
        return stream.getExpiredTime().compareTo(new Date()) < 0;
    }

    public interface StoredLocationBuilder{
        String build(String relativeLocation, SysAuthCode auth);
    }
}
